﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using UnityEngine.UI;

using UnityEngine.Rendering.PostProcessing;

public class PostProcessV2Behavior : MonoBehaviour
{
    public Shader BriShaderDrawMesh;
    private Material briMaterialDrawMesh;
    public Material BriMaterialDrawMesh
    {
        get
        {
            briMaterialDrawMesh = checkShaderAndCreateMaterial(BriShaderDrawMesh, briMaterialDrawMesh);
            return briMaterialDrawMesh;
        }
    }

    private Material checkShaderAndCreateMaterial(Shader s, Material m)
    {
        if (null == s)
            return null;
        if (null != m && m.shader == s)
            return m;

        m = new Material(s);
       // m.hideFlags = HideFlags.DontSave;
        return m;
    }

    static Mesh fullscreenTriangle;
    public static Mesh FullscreenTriangle
    {
        get
        {
            if (fullscreenTriangle != null)
                return fullscreenTriangle;

            fullscreenTriangle = new Mesh { name = "Full Screen Triangle" };

            // Because we have to support older platforms (GLES2/3, DX9 etc) we can't do all of
            // this directly in the vertex shader using vertex ids :(
            fullscreenTriangle.SetVertices(new List<Vector3>
                {
                    new Vector3(-1f, -1f, 0f),
                    new Vector3(-1f,  3f, 0f),
                    new Vector3( 3f, -1f, 0f)
                });
            fullscreenTriangle.SetIndices(new[] { 0, 1, 2 }, MeshTopology.Triangles, 0, false);
            fullscreenTriangle.UploadMeshData(false);
            
            return fullscreenTriangle;
        }
    }

    [Range(0.0f, 3.0f)]
    public float Brightness = 2.0f;
    [Range(0.0f, 3.0f)]
    public float Saturation = 2.0f;
    [Range(0.0f, 3.0f)]
    public float Contrast = 2.0f;


    Camera mainCamera;
    CommandBuffer cmdBuffer;

    RenderTexture screenCopyRT;
    private void Start()
    {
        
    }
    private void OnEnable()
    {
        mainCamera = GetComponent<Camera>();//Camera.main;
        mainCamera.forceIntoRenderTexture = true;
        //mainCamera.targetTexture = null;
        //RenderTexture.ReleaseTemporary(screenCopyRT);
        //screenCopyRT = RenderTexture.GetTemporary(mainCamera.pixelWidth, mainCamera.pixelHeight, 24);
        //mainCamera.targetTexture = screenCopyRT;


        cmdBuffer = new CommandBuffer { name = "Post2222-processing" };
        mainCamera.AddCommandBuffer(CameraEvent.BeforeImageEffects, cmdBuffer);
        

        //mainTexId = Shader.PropertyToID("_ScreenTex");

        //mainCamera.forceIntoRenderTexture = true;
        //mainCamera.allowHDR = true;
        //mainCamera.allowMSAA = true;

        //renderWithDrawmesh();
    }
    private void OnDisable()
    {
        // mainCamera.forceIntoRenderTexture = false;
        cmdBuffer.Clear();
        mainCamera.RemoveCommandBuffer(CameraEvent.BeforeImageEffects, cmdBuffer);
        cmdBuffer = null;
    }

    
    public int mainTexId;
    private bool isInited = false;


   // BloomRenderer BloomRenderer = new BloomRenderer();

    private void OnPreRender()
    {
        //renderWithDrawmesh(cmdBuffer);
        // renderWithBlit();
        cmdBuffer.Clear();
        //BloomRenderer.MyRender(cmdBuffer);
        renderWithDrawmesh(cmdBuffer);

    }
    internal static readonly int testTex = Shader.PropertyToID("_TestTex");
    internal static readonly int MainTex = Shader.PropertyToID("_MainTex");


    //internal static readonly int MainTex = Shader.PropertyToID("_MainTex");
    private void renderWithDrawmesh(CommandBuffer cmd)
    {

        int mipDown = Shader.PropertyToID("_BloomMipDown" + 0);//;, m_Pyramid[0].down;
                                                               //int mipUp = m_Pyramid[0].up;
        int pass = 0;

        //var lastDown = context.source;

        cmd.GetTemporaryRT(mipDown, Screen.width, Screen.height);
        //var cameraTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.CameraTarget);

        //cmd.SetGlobalTexture(MainTex, BuiltinRenderTextureType.CameraTarget);
        //cmd.Blit(MainTex, mipDown, new Material(Shader.Find("Unlit/sCmdTest")), pass);


        cmdBuffer.SetGlobalTexture(MainTex, BuiltinRenderTextureType.CameraTarget);
        //cmdBuffer.Blit(MainTex, BuiltinRenderTextureType.CameraTarget, BriMaterialDrawMesh);
        cmdBuffer.Blit(testTex, mipDown, BriMaterialDrawMesh);

        ////cmdBuffer.Clear();

        //// for (int i = 0; i < 100; i++)
        //{
        //    //cmdBuffer.SetGlobalFloat("_Brightness", Brightness);
        //    //cmdBuffer.SetGlobalFloat("_Saturation", Saturation);
        //    //cmdBuffer.SetGlobalFloat("_Contrast", Contrast);

        //    //cmdBuffer.GetTemporaryRT(testTex, mainCamera.pixelWidth, mainCamera.pixelHeight);


        //    //cmdBuffer.Blit(BuiltinRenderTextureType.CameraTarget, testTex);
        //    /////
        //    //var cameraTarget = new RenderTargetIdentifier(BuiltinRenderTextureType.CameraTarget);

        //    //cmdBuffer.SetGlobalTexture(MainTex, cameraTarget);
        //    cmdBuffer.SetGlobalTexture(MainTex, BuiltinRenderTextureType.CameraTarget);



        //    //var sheet = context.propertySheets.Get("Unlit/sCmdTest");
        //    //cmdBuffer.Blit(MainTex, mipDown, sheet.material, pass);

        //    /////

        //    // cmdBuffer.SetRenderTarget(BuiltinRenderTextureType.CameraTarget, RenderBufferLoadAction.DontCare, RenderBufferStoreAction.Store);
        //    //cmdBuffer.SetViewport(mainCamera.pixelRect);
        //    //cmdBuffer.DrawMesh(FullscreenTriangle, Matrix4x4.identity, BriMaterialDrawMesh);
        //    cmdBuffer.Blit(MainTex, BuiltinRenderTextureType.CameraTarget, BriMaterialDrawMesh);

        // cmdBuffer.ReleaseTemporaryRT(mainTexId);
    }


        //}



        //private void renderWithBlit()
        //{
        //    cmdBuffer.Clear();
        //    var cameraTarget = BuiltinRenderTextureType.CameraTarget;

        //    cmdBuffer.SetGlobalFloat("_Brightness", Brightness);
        //    cmdBuffer.SetGlobalFloat("_Saturation", Saturation);
        //    cmdBuffer.SetGlobalFloat("_Contrast", Contrast);

        //    cmdBuffer.GetTemporaryRT(mainTexId, mainCamera.pixelWidth, mainCamera.pixelHeight);
        //    // var flipMat = new Material(Shader.Find("Hidden/BlitCopy"));
        //    cmdBuffer.Blit(BuiltinRenderTextureType.CurrentActive, mainTexId );

        //    cmdBuffer.Blit(mainTexId, cameraTarget, BriMaterialDrawMesh);

        //    cmdBuffer.ReleaseTemporaryRT(mainTexId);
        
    }
